import { useEffect, useState } from "react";
import { Button, ConfigProvider, Modal, Table, Tooltip, message } from "antd";
import styles from "@/styles/Evaluation.module.css";
import EvaluationChart from "@/components/evaluationChart";
import { TableRowSelection } from "antd/es/table/interface";
import Column from "antd/es/table/Column";

type ResData = {
  results: {
    id: number;
    createdAt: string;
    dataset: {
      name: string;
      origin: string;
      noise: number;
    };
    indicator1: number;
    indicator2: number;
  }[];
};

type DataType = {
  id: number;
  origin: string;
  name: string;
  noise: number;
  createdAt: string;
  indicator1: number;
  indicator2: number;
};

export default function Evaluation() {
  const [standardData, setStandardData] = useState<DataType[]>([]);
  const [testData, setTestData] = useState<DataType[]>([]);
  useEffect(() => {
    (async () => {
      getStandardData();
      getTestData();
    })();
  }, []);

  async function getStandardData() {
    const res = await fetch(`http://localhost:3000/test/result?standard=true`);
    const data: ResData = await res.json();
    setStandardData(
      data.results.map((item) => {
        return {
          id: item.id,
          origin: item.dataset.origin,
          name: item.dataset.name,
          noise: item.dataset.noise,
          createdAt: item.createdAt,
          indicator1: item.indicator1,
          indicator2: item.indicator2,
        };
      })
    );
  }

  async function getTestData() {
    const res = await fetch(`http://localhost:3000/test/result`);
    const data: ResData = await res.json();
    setTestData(
      data.results.map((item) => {
        return {
          id: item.id,
          origin: item.dataset.origin,
          name: item.dataset.name,
          noise: item.dataset.noise,
          createdAt: item.createdAt,
          indicator1: item.indicator1,
          indicator2: item.indicator2,
        };
      })
    );
  }

  // 表格选择
  const [selectedStandard, setSelectedStandard] = useState<DataType[]>([]);
  const [selectedTest, setSelectedTest] = useState<DataType[]>([]);
  const standardSelection: TableRowSelection<DataType> = {
    selections: [Table.SELECTION_ALL, Table.SELECTION_NONE],
    onChange: (_selectedRowKeys, selectedRows) => {
      setSelectedStandard(selectedRows);
    },
  };
  const testSelection: TableRowSelection<DataType> = {
    selections: [Table.SELECTION_ALL, Table.SELECTION_NONE],
    onChange: (_selectedRowKeys, selectedRows) => {
      setSelectedTest(selectedRows);
    },
  };

  // 鲁棒性指标
  const [d1, setD1] = useState(0);
  const [d2, setD2] = useState(0);

  // 计算性能下降20%的点
  const calculateD = (results: DataType[]) => {
    const start = results[0].indicator1;
    for (let i = 0; i < results.length; i++) {
      const now = results[i].indicator1;
      if (Math.abs(start - now) > 0.2) return results[i].noise;
    }

    return results.at(-1)!.noise;
  };

  // 控制泛化性和鲁棒性指标显示模态框
  const [isGenModalOpen, setIsGenModalOpen] = useState(false);
  const [isRobModalOpen, setIsRobModalOpen] = useState(false);

  const showGenModal = () => {
    if (selectedStandard.length < 1) {
      message.warning("至少选择一条标准数据");
    } else if (selectedStandard.length > 1) {
      message.warning("只能选择一条标准数据");
    } else if (selectedTest.length < 1) {
      message.warning("至少选择一条测试数据");
    } else {
      setIsGenModalOpen(true);
    }
  };

  const showRobModal = () => {
    if (selectedStandard.length < 1) {
      message.warning("至少选择一条标准数据");
    } else if (selectedStandard.length !== selectedTest.length) {
      // TODO 修改判断条件
      message.warning("标准数据和测试数据干扰不一致");
    } else {
      setD1(calculateD(selectedStandard));
      setD2(calculateD(selectedTest));
      setIsRobModalOpen(true);
    }
  };

  return (
    <ConfigProvider
      theme={{
        components: {
          Table: {
            fontSize: 14,
          },
        },
      }}
    >
      <div className={styles.toolBar}>
        <Button type="primary" onClick={showGenModal}>
          泛化性评估
        </Button>
        <Button type="primary" onClick={showRobModal}>
          鲁棒性评估
        </Button>
      </div>
      <div className={styles.twoCol}>
        <Table
          rowSelection={standardSelection}
          rowKey={(record) => record.id}
          dataSource={standardData}
          bordered
          scroll={{ y: 680 }}
        >
          <Column
            title="序号"
            dataIndex="index"
            key="index"
            align="center"
            width={70}
            render={(_text, _record, index) => `${index + 1}`}
          />
          <Column
            title="类型"
            dataIndex={"type"}
            key={"type"}
            align="center"
            render={() => <div style={{ color: "#0958d9" }}>{"标准数据"}</div>}
          />
          <Column
            title="数据集"
            dataIndex="name"
            key="name"
            align="center"
            render={(text) => (
              <Tooltip title={text}>
                <div
                  style={{
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            )}
          />
          <Column
            title="原始数据集"
            dataIndex="origin"
            key="origin"
            align="center"
          />
          <Column
            title="干扰(%)"
            dataIndex="noise"
            key="noise"
            width={90}
            align="center"
          />
          <Column
            title="mAP0.5"
            dataIndex="indicator1"
            key="indicator1"
            align="center"
          />
          <Column
            title="mAP50_95"
            dataIndex="indicator2"
            key="indicator2"
            align="center"
          />
        </Table>
        <Table
          rowSelection={testSelection}
          rowKey={(record) => record.id}
          dataSource={testData}
          bordered
          scroll={{ y: 680 }}
        >
          <Column
            title="序号"
            dataIndex="index"
            key="index"
            align="center"
            width={70}
            render={(_text, _record, index) => `${index + 1}`}
          />
          <Column
            title="类型"
            dataIndex={"type"}
            key={"type"}
            align="center"
            render={() => <div style={{ color: "#389e0d" }}>{"测试数据"}</div>}
          />
          <Column
            title="数据集"
            dataIndex="name"
            key="name"
            align="center"
            width={90}
            render={(text) => (
              <Tooltip title={text}>
                <div
                  style={{
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  }}
                >
                  {text}
                </div>
              </Tooltip>
            )}
          />
          <Column
            title="原始数据集"
            dataIndex="origin"
            key="origin"
            align="center"
            filters={Array.from(
              new Set(testData.map((item) => item.origin))
            ).map((item) => {
              return { text: item, value: item };
            })}
            onFilter={(value, record: DataType) => {
              return value === record.origin;
            }}
          />
          <Column
            title="干扰(%)"
            dataIndex="noise"
            key="noise"
            align="center"
            width={90}
          />
          <Column
            title="mAP0.5"
            dataIndex="indicator1"
            key="indicator1"
            align="center"
          />
          <Column
            title="mAP50_95"
            dataIndex="indicator2"
            key="indicator2"
            align="center"
          />
        </Table>
      </div>
      <Modal
        key="genModal"
        open={isGenModalOpen}
        onOk={() => setIsGenModalOpen(false)}
        onCancel={() => setIsGenModalOpen(false)}
        width={750}
      >
        <EvaluationChart
          type="gen"
          title="mAP0.5"
          realResults={selectedStandard.map((item) => item.indicator1)}
          virtualResults={selectedTest.map((item) => item.indicator1)}
          xAxis={selectedTest.map((item) => item.origin)}
        ></EvaluationChart>
        <EvaluationChart
          type="gen"
          title="mAP50_95"
          realResults={selectedStandard.map((item) => item.indicator2)}
          virtualResults={selectedTest.map((item) => item.indicator2)}
          xAxis={selectedTest.map((item) => item.origin)}
        ></EvaluationChart>
      </Modal>
      <Modal
        key="robModal"
        open={isRobModalOpen}
        onOk={() => setIsRobModalOpen(false)}
        onCancel={() => setIsRobModalOpen(false)}
        width={750}
      >
        <EvaluationChart
          type="rob"
          title="mAP0.5"
          realResults={selectedStandard.map((item) => item.indicator1)}
          virtualResults={selectedTest.map((item) => item.indicator1)}
          xAxis={selectedTest.map((item) => item.noise.toString())}
          d1={d1}
          d2={d2}
        ></EvaluationChart>
        <div className={styles.indicators}>
          <div>{`干扰强度d1: ${d1}%`}</div>
          <div>{`干扰强度d2: ${d2}%`}</div>
          <div>{`e:${((Math.abs(d1 - d2) / d1) * 100).toFixed(5)}%`}</div>
        </div>
      </Modal>
    </ConfigProvider>
  );
}
